package com.mpp.admin.shiro;

import com.mpp.admin.entity.OnLineUser;
import com.mpp.admin.entity.User;
import com.mpp.admin.util.Constant;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Map;

/**
 * @author mapp
 * @des 自定义shiro默认表单认证过滤器
 * @date 2019/2/18
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    // 访问被拒绝后处理
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return super.onAccessDenied(request, response);
    }

    // 登录成功后默认跳转/index 页面。 shiro默认会请求上一次被拒绝的请求。这里只返回/index。
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        // 登录成功后请求
        String successUrl = this.getSuccessUrl();

        if (successUrl == null) {
            throw new IllegalStateException("Success URL not available via saved request or via the successUrlFallback method parameter. One of these must be non-null for issueSuccessRedirect() to work.");
        } else {
            // 放入session
            Session session = subject.getSession(true);
            User user = (User) subject.getPrincipal();
            OnLineUser onLineUser = new OnLineUser();
            onLineUser.setSessionId((String) session.getId());
            onLineUser.setUsername(user.getUsername());
            onLineUser.setStatus("1");
            onLineUser.setHost(session.getHost());

            session.setAttribute(Constant.SHIRO_SESSION_ATTR, onLineUser);
            WebUtils.issueRedirect(request, response, successUrl, (Map)null, true);
        }
        return false;
    }
}
